'''
Created on 2021年1月15日

@author: Administrator
'''
import datetime,time

from common.public import *
from orm.model import db, DiscountListDetail, DiscountList, Customer,TransForm
from view.baseview import BaseView
from peewee import JOIN, fn


class DisCountListView(BaseView):

    def __init__(self):
        pass
  
    def queryDiscountList(self, params):
        """根据条件取得我的客户列表，params：条件参数"""
        result = []
        where_condition = True
        print(params)
        if params["applicantId"]:
            where_condition = where_condition & (DiscountList.applicant_id == params["applicantId"])
        if params["status"]:
            where_condition = where_condition & (DiscountList.status == params["status"])
        if params["createTime"]:
            where_condition = where_condition & ((DiscountList.create_time >= params["createTime"][0] + " 00:00:00") \
                                               & (DiscountList.create_time <= params["createTime"][1] + " 23:59:59"))
        rows = DiscountList.select().where(where_condition).order_by(DiscountList.create_time.desc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        
#         rows = DiscountList.select().join(Customer, JOIN.LEFT_OUTER, on = (WorkOrder.customer_id == Customer.id))\
#         .join(ServiceDetail, JOIN.LEFT_OUTER, on = (WorkOrder.servicedetail_id == ServiceDetail.id))\
#         .where(where_condition).paginate(int(params["pageNo"]), int(params["pagesize"]))
        total = rows.count()
        for row in rows:
            customerrow = Customer.select().where(Customer.id == row.customer_id).first()
            compname = ""
            if customerrow:
                compname = customerrow.compname
            if row.create_time != None:
                row.create_time = time.strftime("%Y-%m-%d", time.strptime(str(row.create_time), "%Y-%m-%d %H:%M:%S"))
            if row.update_time != None:
                row.update_time = time.strftime("%Y-%m-%d", time.strptime(str(row.update_time), "%Y-%m-%d %H:%M:%S"))
            if row.end_date != None:
                row.end_date = time.strftime("%Y-%m-%d", time.strptime(str(row.end_date), "%Y-%m-%d %H:%M:%S"))
            discountdetailsrows = DiscountListDetail.select().where((DiscountListDetail.discount == row.id))
            recs = []
            for discountdetailsrow in discountdetailsrows:
                if discountdetailsrow.create_time != None:
                    discountdetailsrow.create_time = time.strftime("%Y-%m-%d", time.strptime(str(discountdetailsrow.create_time), "%Y-%m-%d %H:%M:%S"))
                if discountdetailsrow.update_time != None:
                    discountdetailsrow.update_time = time.strftime("%Y-%m-%d", time.strptime(str(discountdetailsrow.update_time), "%Y-%m-%d %H:%M:%S"))
                recs.append({"id":discountdetailsrow.id,
                 "discountId":discountdetailsrow.discount.id,
                 "serviceId":discountdetailsrow.service.id,
                 "servicename":discountdetailsrow.service.name,
                 "spec":discountdetailsrow.servicedetail.spec, 
                 "type":discountdetailsrow.servicedetail.type, 
                 "servicedetailId":discountdetailsrow.servicedetail.id,
                 "price":discountdetailsrow.servicedetail.price,
                 "unit":discountdetailsrow.servicedetail.unit,
                 "amount":discountdetailsrow.amount,
                 "priceb":discountdetailsrow.priceb,
                 "pricea":discountdetailsrow.pricea,
                "remake":discountdetailsrow.remake,
                "updateTime":discountdetailsrow.update_time,
                "createTime":discountdetailsrow.create_time
                             })
            if recs.__len__() == 0:
                recs = []
            # isover = "是"
            # if datetime.datetime.strptime(row.end_date + " 00:00:00",'%Y-%m-%d %H:%M:%S') > datetime.datetime.now():
            #     isover = "否"
            data = {
                "id":row.id,
                "applicant":row.applicant.username,
                "compname":compname,
                "applicantId":row.applicant.id,
                "leader":row.leader.username,
                "leaderId":row.leader.id,
                "leaderstatus":row.leader.username + "[" + row.leaderstatus + "]",
                "manager":row.manager.username,
                "managerId":row.manager.id,
                "managerstatus":row.manager.username + "[" + row.managerstatus + "]",
                "status":row.status,
                # "isover": isover,
                "type": row.type,
#                 "price":row.price,
#                 "newprice":row.new_price,
                "preferentialDescription":row.preferential_description,
                "createTime":row.create_time,
                "updateTime":row.update_time,
                "enddate":row.end_date,
                "recs":recs
             }
            result.append(data)
        return super().resultSet(200, "", result, total)

    @db.atomic()                   
    def nopass(self, params):
        """
        驳回
        """
        discountlist = DiscountList.get(DiscountList.id == params["id"])
        if int(params["userid"]) == params["leaderId"]:
            discountlist.leaderstatus = AUDIT_STATUS_CANCLE
        if int(params["userid"]) == params["managerId"]:
            discountlist.managerstatus = AUDIT_STATUS_CANCLE
        discountlist.status = AUDIT_STATUS_CANCLE
        discountlist.save()
        return super().resultSet(200, "已驳回,请重新申请。", [])
        raise Exception("驳回失败。")
         
    @db.atomic()                   
    def approve(self, params):
        """
        审核通过
        """
        print("approve")
        print(params)
        discountlist = DiscountList.get(DiscountList.id == params["id"])
        if int(params["userid"]) == params["leaderId"] and discountlist.leaderstatus == AUDIT_STATUS_WAITE:
            # 主管 
            discountlist.leaderstatus = AUDIT_STATUS_PASSED
            discountlist.managerstatus = AUDIT_STATUS_WAITE
        elif int(params["userid"]) == params["managerId"] and discountlist.managerstatus == AUDIT_STATUS_WAITE:
            # 经理
            if discountlist.leaderstatus == AUDIT_STATUS_PASSED:
                # 如果主管已审核
                discountlist.managerstatus = AUDIT_STATUS_PASSED
            else:
                # 如果主管未审核
                return super().resultSet(201, "主管还未审核通过,您无法操作。", [])

        if  discountlist.leaderstatus == AUDIT_STATUS_PASSED \
            and discountlist.managerstatus == AUDIT_STATUS_PASSED:
            # 如果主管,经理都审核通过，状态改为已审核
            discountlist.status = AUDIT_STATUS_PASSED
 
        discountlist.save()
        return super().resultSet(200, "审核通过", [])
        raise Exception("审核失败")

    @db.atomic()                   
    def apply(self, params):
        """
        申请优惠单
        """
        print(params)
        discountlist = DiscountList.create(
                customer_id = params["customerId"],
                applicant_id = params["applicantId"],
                leader_id = params["leaderId"],
                leaderstatus = AUDIT_STATUS_WAITE,
                manager_id = params["managerId"],
                managerstatus = AUDIT_STATUS_WAITE,
                status = AUDIT_STATUS_WAITE,
                type = params["type"],
#                 price = params["price"],
#                 new_price = params["newprice"],
                preferential_description = params["preferentialDescription"],
                end_date = (datetime.datetime.now() + datetime.timedelta(days=14)).strftime("%Y-%m-%d %H:%M:%S"),
                del_flag = NOTDELFLAG,
                create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            )
        discountlist.save()
        for item in params["recs"]:
            print(item)
            print(item["serviceId"])
            discountlistdetail = DiscountListDetail.create(
                    discount_id = discountlist.id,
                    service_id = item["serviceId"],
                    servicedetail_id = item["id"],
                    amount = item["amount"],
                    pricea = item["pricea"],
                    priceb = item["priceb"],
                    remake = item["memo"],
                    create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                )
            discountlistdetail.save()
        return super().resultSet(200, "申请成功", [])
        raise Exception("申请失败。")
         
    @db.atomic()                   
    def remove(self, params):
        """
        作废优惠单
        """
        discountlist = DiscountList.get(DiscountList.id == params["id"])
        if int(params["userid"]) == int(params["leaderId"]):
            discountlist.leaderstatus = AUDIT_STATUS_OVER
        elif int(params["userid"]) == int(params["managerId"]):
            discountlist.managerstatus = AUDIT_STATUS_OVER
        # else:
        #     return super().resultSet(201, "作废失败", [])
        discountlist.status = AUDIT_STATUS_OVER
        discountlist.save()
        return super().resultSet(200, "作废成功", [])
        raise Exception("作废失败。")

    def getList(self, customerid):
        """根据客户ID取得优惠单列表，params：条件参数"""
        result = []
        rows = DiscountList.select().join(TransForm, JOIN.LEFT_OUTER, on = (TransForm.discount_id == DiscountList.id))\
                .where((DiscountList.customer_id == customerid) \
                & (DiscountList.status == AUDIT_STATUS_PASSED))
        result.append({
            "id": 0,
            "preferentialDescription": "无",
            "detail": []
        })
        for row in rows:
            discount = {
                    "id":row.id,
                    "preferentialDescription":row.preferential_description,
                    "detail":[]
            }
            for srow in row.discountlistdetail_set:
                data = {
                     "serviceid":srow.service_id,
                     "servicedetailid":srow.servicedetail_id,
                     "amount":srow.amount,
                     # 优惠前价格
                     "priceb":srow.priceb,
                     # 优惠后价格
                     "pricea":srow.pricea,
                 }
                discount['detail'].append(data)
            result.append(discount)
        return super().resultSet(200, "", result)

